import { HttpException, HttpStatus } from '@nestjs/common';
import { ErrorCodeEnum } from '../enums/error-code.enum';
import { ResponseCodeEnum } from '../enums/response-code.enum';

export class BusinessException extends HttpException {
  private errorCode: number;
  constructor(error: string | ErrorCodeEnum) {
    if (error.includes(':')) {
      const [code, message] = error.split(':');
      super(
        {
          code,
          message,
          data: null,
        },
        HttpStatus.OK, // HTTP 状态码始终返回 200，错误信息通过 code 字段区分
      );
      this.errorCode = Number(code);
      return;
    }

    super(
      {
        code: ResponseCodeEnum.FAIL,
        message: error,
        data: null,
      },
      HttpStatus.OK, // HTTP 状态码始终返回 200，错误信息通过 code 字段区分
    );
    this.errorCode = ResponseCodeEnum.FAIL;
  }

  getErrorCode() {
    return this.errorCode;
  }
}
